package com.ibiaoke.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.function.Function;

/**
 * Created by huhaichao on 2017/6/29.
 */
public class DateUtils {

    public static String ORDER_NO_FORMAT="yyyyMMddHHmmss";
    public static String SIMPLE_FORMAT="yyyy-MM-dd HH:mm:ss";

    public static String format(Date date, String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(date);
    }

    public static String formatSimpleDate(Date date){
       return format(date,SIMPLE_FORMAT);
    }

    public static Date parseDate(String date, String pattern){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        try {
            return simpleDateFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Date parseSimpleDate(String date){
        return parseDate(date,SIMPLE_FORMAT);
    }


    public static String formatOrderNoDate(Date date){
        return format(date,ORDER_NO_FORMAT);
    }

    /**
     * 获取今天加上天数偏移0点时间
     * @param dayOffset 天数偏移量
     * @return
     */
    public static  Date theDayBegin(int dayOffset){
        return theDayBegin(new Date(),dayOffset);
    }

    /**
     * 返回一个指定日期的偏移函数
     * @param date
     * @return
     */
    public static Function<Integer,Date> theDayBeginFun(Date date){
        return dayOffset->theDayBegin(date,dayOffset);
    }

    /**
     * 获取一天中的0点时间
     * @param dayOffset 天数偏移量
     * @return
     */
    public static  Date theDayBegin(Date date,int dayOffset){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH,dayOffset);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
       return calendar.getTime();
    }

    /**
     * 给日期增加时间
     * @param date
     * @param field
     * @param value
     * @return
     */
    public static  Date add(Date date,int field,int value){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(field,value);
        return calendar.getTime();
    }

    /**
     *
     * @param field the calendar field.
     * @param amount amount to be added to the field.
     * @return
     */
    public static  Date add(int field,int amount){
        Calendar calendar = Calendar.getInstance();
        calendar.add(field,amount);
        return calendar.getTime();
    }
}
